<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;
use Cache;
use Log;
use Redis;

class MyApiController extends Controller
{
	//获取阿里大于key和secret
	public function getDyKeySecret()
	{
		$redis = Redis::connection('public');
		if ($redis->exists('alidysmsKeySec') === 0) {
			$seconds = 60 * 60 * 24; //token缓存的时间，单位 秒
			$json = json_encode(['_key' => config('constant.alidysms_key'), '_secret' => config('constant.alidysms_secret')]);
			$redis->set('alidysmsKeySec', $json, 'EX', $seconds);
		}
		return $redis->get('alidysmsKeySec');
	}
    // 根据工器具rfid 获取工器具的详细检测信息  杭州工具柜厂家
    public function getDetailTestInfoByRFID(Request $request)
    {
        // return redirect("/admin/itemData/view?id={$request->id}");
        $rfid = $request->rfid;
        //获取 sample_info 的id
        $date = $request->date;
        // $key = $request->k; //密钥

        if ($request->isMethod('POST')) {
            //
        } else {
            $sample_info_data = null;
            if ($rfid) {
                # code...
                if ($date === null) {
                    # 没有指定试验日期就返回最新的
                    $sample_info_data = DB::table('a_sample_info')->where('gqj_ID', $rfid)->orderBy('test_time', 'desc')->first();
                } else {
                    $sample_info_data = DB::table('a_sample_info')->where('gqj_ID', $rfid)->where('test_time', $date)->first();
                }
            }
            if (!$sample_info_data) {
                # 如果返回null,直接返回
                return '未查到记录';
            }
            // if ($sample_info_data->key != $request->k) {
            //     return "<h1 style='margin-top:200px;padding-left:50px'>密钥错误</h1>";
            // }

            $gaiyao_data = DB::table('a_contract_gaiyao')->find($sample_info_data->contract_gaiyao_id);
            $cycle = DB::table('a_std_tool_rel')->where('std_id', $gaiyao_data->std_id)->where('tool_id', $gaiyao_data->tool_id)->value('cycle'); //周期
            //  $contract_id = $sample_info_data->contract_id; //批次 id
            //获取下一个样品的id
            //  $sample_id_next = DB::table('a_sample_info')->where('id', '>', $sample_info_id)->where('contract_id', $contract_id)->orderBy('id', 'asc')->value("id");
            //获取上一个样品的id
            //  $sample_id_pre = DB::table('a_sample_info')->where('id', '<', $sample_info_id)->where('contract_id', $contract_id)->orderBy('id', 'desc')->value("id");

            $sql = "SELECT
                           A.id,
                           A.item_id,
                           A.wea,
                           A.pressure,
                           A.temp,
                           A.hum,
                           A.res,
                           A.manager_id,
                           A.device_ids,
                           B.`name`,
                           C.realname,
                           D.std_id,
                           D.tool_id
                       FROM
                           a_item_data AS A
                           LEFT JOIN a_testitem AS B ON A.item_id = B.id
                           LEFT JOIN manager AS C ON A.manager_id = C.id
                           LEFT JOIN a_contract_gaiyao AS D ON A.contract_gaiyao_id = D.id
                           LEFT JOIN a_std_tool_item_rel AS E ON D.std_id = E.std_id
                           AND D.tool_id = E.tool_id
                           AND A.item_id = E.testitem_id
                       WHERE
                           A.sample_info_id = :sample_info_id
                       ORDER BY
                           E.sort ASC";

            $items_data = DB::select($sql, ['sample_info_id' => $sample_info_data->id]);
            //历史信息
            if ($sample_info_data->gqj_ID !== '' && intval($sample_info_data->gqj_ID) !== 0) {
                $history = DB::table('a_sample_info')
                    ->where('bar_code', '!=', $sample_info_data->bar_code)
                    ->where('gqj_ID', $sample_info_data->gqj_ID)
                    ->whereNotNull('test_time')
                    ->select('test_time', 'id', 'key', 'gqj_ID')
                    ->orderBy('test_time', 'desc')->get();
            } else {
                $history = [];
            }
            //获取批次的详细信息
            return view('admin.myApi.viewRes', compact('items_data', 'sample_info_data', 'gaiyao_data', 'cycle', 'history'));
        }
    }

    /* 根据工器具id 获取工器具最近一次检测的结论  杭州工具柜厂家 */
    public function getConclusionByRFID(Request $request)
    {
        $rfid = $request->rfid;
        $res = null;
        if ($rfid) {
            # code...
            $res = DB::table('a_sample_info')->where('gqj_ID', $rfid)->orderBy('test_time', 'desc')->value('res');
        }

        $arr = [];

        if ($res === null) {
            $arr = ['code' => 1, 'msg' => '此工器具不存在'];
        } else {
            $arr = ['code' => 0, 'conclusion' => $res];
        }
        return response()->json($arr);
    }

    /* 更新烟雾报警信息 VB软件请求的接口*/
    public function updateSmokeAlarm(Request $request)
    {
        $value = $request->value; //使用中为1，未使用为0
        $res = DB::table('setting_sys')->where('key', 'is_smoke_alarm')->update(['value' => $value]);

        return $res >= 0 ? '1' : '0';
    }

    /* 大屏获取环境信息 */
    public function getEnvInfo(Request $request)
    {
        // response()->header('Access-Control-Allow-Origin', '*');
        // response()->header('Access-Control-Allow-Headers', 'Origin, Content-Type, Cookie, X-CSRF-TOKEN, Accept, Authorization, X-XSRF-TOKEN');
        // response()->header('Access-Control-Expose-Headers', 'Authorization, authenticated');
        // response()->header('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, OPTIONS');
        // response()->header('Access-Control-Allow-Credentials', 'true');
        $date = date('Y-m-d H:i:s', strtotime('-30 minute'));
        // header("Access-Control-Allow-Origin: *");//如果是跨域请求需要加上此行
        $key = $request->key;
        $data = DB::table('a_env_info')->select('temp', 'humi', 'pressure', 'time')->where('hb6303_id', $key)->where('time', '>', $date)->where('temp', '!=', '')->orderBy('id', 'desc')->first();
        if (!$data) {
            $data = 'none';
        }
        return response()->json($data);
    }
    /* 获取HB6303温湿度模块的----温度 */
    public function getTemp(Request $request)
    {
        // sleep(1);
        $temp_data = DB::table('a_env_info')->select('id', 'temp', 'time')->where('hb6303_id', 1)->orderBy('id', 'desc')->limit(1000)->get();
        // dd($temp_data);
        // dd($temp_data->count());
        $count = $temp_data->count();
        $temp = [];
        $time = [];
        foreach ($temp_data as $k => $v) {
            $temp[] = $temp_data[$count - 1 - $k]->temp;
            $aa = $temp_data[$count - 1 - $k]->time;
            $time[] = date('i:s', strtotime($aa));
        }
        $data['time'] = $time;
        $data['temp'] = $temp;

        return response()->json($data);
    }
    /* HB6303温湿度模块上传数据 */
    public function hb6303(Request $request)
    {
        // Log::info('myapicon/hb6303   gwwHB6303--数据上传'); //该方法会将日志全部记录在 storage/logs/laravel.log 文件里，这样的问题是当日志文件比较多的时候查找起来比较麻烦
        // Log::info($request->all()); //该方法会将日志全部记录在 storage/logs/laravel.log 文件里，这样的问题是当日志文件比较多的时候查找起来比较麻烦
        try {
            //code...
            $temp = $request->temp;
            $humi = $request->humi;
            $pressure = $request->query('pressure','');
            $dev_num = $request->dev_num;

            if (config('constant.app_name') == "HuiBangJianCe") {
                # 汇邦检测的项目，HB6303没有大气压就获取青萍的大气压
                if ($pressure == "") {
                    $dateP = date('Y-m-d H:i:s', strtotime('-59 minute'));
                    $pressure = DB::table('a_env_info')->where('hb6303_id', '=', 1)
                        ->where('time', '>', $dateP)->where('pressure', '!=', '')->orderBy('id', 'desc')->value('pressure');
                }
            }

            $hb6303_id = DB::table('a_hb6303')->where('dev_num', $dev_num)->value('id');
            if ($hb6303_id) {
                # code...
                $hb6303_interval = DB::table('setting_sys')->where('key', 'hb6303_interval')->value('value');
                $hb6303_interval = sprintf('%04d', $hb6303_interval);

                DB::table('a_env_info')->insert([
                    'temp' => number_format($temp,1,".",""),
                    'humi' => number_format($humi,1,".",""),
                    'pressure' => number_format($pressure,2,".",""),
                    'dev_num' => $dev_num,
                    'hb6303_id' => $hb6303_id
                ]);

                $res = 'start{' . $hb6303_interval . '}end';
            } else {
                $res = 'This devNum is not exist in database';
            }
        } catch (\Throwable $th) {
            //throw $th;
            $res = 'error';
        }
        //新版本必须传new参数
        if(isset($request->new)){
            header('Content-Length:'.strlen($res));
        }
        return $res;
    }
    /* ajax 根据样品ID 获取 检验标准 */
    public function getStdParam(Request $request)
    {
        //接收样品的 ID
        $tool_id = $request->id;
        //返回json数据
        $data['data_std'] = DB::table('a_standard as a')
                              ->leftJoin('a_std_tool_rel as b', 'b.std_id', '=', 'a.id')
                              ->where('b.tool_id', $tool_id)
                              ->where('a.ishide', '0')
                              ->orderBy('b.sort', 'asc')
                              ->select('a.id', 'a.num')->get();

        //更新工器具 表的 stamp 字段（用于将最近点击过的工器具显示在前面）
        $res = DB::table('a_tool')->where('id', $tool_id)->update(['stamp' => time()]);

        return response()->json($data);
    }
    /* ajax 根据样品ID 和 标准ID 获取 检验项目、额定电压、分类 */
    public function getItem(Request $request)
    {
        //接收样品的 ID
        $tool_id = $request->tool_id;
        $std_id = $request->std_id;

        $data_vol = DB::table('a_voltage_class')->select('id', 'val','cycle')->where('std_id', $std_id)->where('tool_id', $tool_id)->where('type', '0')->where('ishide', '0')->orderBy('sort')->get()->keyBy('id');
        $data_class = DB::table('a_voltage_class')->select('id', 'val','cycle')->where('std_id', $std_id)->where('tool_id', $tool_id)->where('type', '1')->where('ishide', '0')->orderBy('sort')->get()->keyBy('id');

        //得到 与当前的工器具关联的所有检验项目的 数组
        // $arr_item_id = DB::table('a_std_tool_item_rel')->where('std_id', $std_id)->where('tool_id', $tool_id)->pluck('testitem_id');
        // $data_item = DB::table('a_testitem')->select('id', 'name')->whereIn('id', $arr_item_id)->where('ishide', '0')->get();
        $sql = "SELECT
                    C.id,
                    C.`name`
                FROM
                    a_std_tool_item_rel AS A
                    LEFT JOIN a_testitem AS C ON A.testitem_id = C.id
                WHERE
                    A.std_id = :std_id
                    AND A.tool_id = :tool_id
                    AND A.ishide = 0
                    AND C.ishide = 0
                ORDER BY
                    A.sort ASC";

        $data_item = DB::select($sql, ['std_id' => $std_id, 'tool_id' => $tool_id]);

        $data['data_vol'] = $data_vol;
        $data['data_class'] = $data_class;
        $data['data_item'] = $data_item;
        $data['cycle'] = DB::table('a_std_tool_rel')->where(['std_id'=>$std_id,'tool_id'=>$tool_id])->value('cycle');
        //返回json数据
        return response()->json($data);
    }
    /* ajax 根据批次概要ID 获取 检验项目 */
    public function getItemByContractGaiyaoId(Request $request)
    {
        $gaiyao_id = $request->id;

        $str_item_ids = DB::table('a_contract_gaiyao')->where('id', $gaiyao_id)->value('item_ids');
        $arr_item_id = explode(',', $str_item_ids); //把字符串分割为数组
        $data_item = DB::table('a_testitem')->select('id', 'name')->whereIn('id', $arr_item_id)->orderBy(DB::raw("field(id,{$str_item_ids})"))->get();

        //返回json数据
        return response()->json($data_item);
    }
    /* 查看 任务分配结果 */
    public function viewAssignRes(Request $request)
    {
        $gaiyao_id = $request->id;

        $sql = "SELECT
                    tabA.*, a_testitem.name,
                    manager.realname
                FROM
                    (
                        SELECT DISTINCT
                            a_item_data.item_id,
                            a_item_data.allot_time,
                            a_item_data.manager_id
                        FROM
                            a_item_data
                        WHERE
                            contract_gaiyao_id = :gaiyao_id
                    ) AS tabA
                LEFT JOIN a_testitem ON tabA.item_id = a_testitem.id
                LEFT JOIN manager ON tabA.manager_id = manager.id";

        $data = DB::select($sql,['gaiyao_id'=>$gaiyao_id]);
        // dd($data);
        return view('admin.myApi.viewAssignRes', compact('data'));
    }



    /* 获取客户端真实的IP地址 */
    private function get_real_ip()
    {
        $ip = FALSE;
        //客户端IP 或 NONE
        if (!empty($_SERVER["HTTP_CLIENT_IP"])) {
            $ip = $_SERVER["HTTP_CLIENT_IP"];
        }

        //多重代理服务器下的客户端真实IP地址（可能伪造）,如果没有使用代理，此字段为空
        if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ips = explode(", ", $_SERVER['HTTP_X_FORWARDED_FOR']);
            if ($ip) {
                array_unshift($ips, $ip);
                $ip = FALSE;
            }

            for ($i = 0; $i < count($ips); $i++) {
                if (!eregi("^(10│172.16│192.168).", $ips[$i])) {
                    $ip = $ips[$i];
                    break;
                }
            }
        }

        //客户端IP 或 (最后一个)代理服务器 IP
        return ($ip ? $ip : $_SERVER['REMOTE_ADDR']);
    }

    /* 获取实时天气 */
    public function getWeather()
    {
        // Cache::flush();//清除所有缓存
        $minutes = 30; //天气缓存的时间，单位分钟
        $weather_arr = Cache::remember('weather', $minutes, function () {
            $city_id = "101090208";
            $ip = $this->get_real_ip();
            //必须指定IP，否则返回的是服务器所在地的天气
            $url = "https://www.tianqiapi.com/api/?version=v6&ip=$ip";

            $weatherContent = file_get_contents($url);
            $all_weather_arr = json_decode($weatherContent, true);
            $weather_arr['wea'] = $all_weather_arr['wea'];
            $weather_arr['city'] = $all_weather_arr['city'];
            $weather_arr['pressure'] = $all_weather_arr['pressure'] / 10;
            // $weather_arr['tem'] = $all_weather_arr['tem'];
            return $weather_arr;
        });
        return response()->json($weather_arr);
    }

    /*获取实时烟雾报警*/
    public function getSmokeStatus()
    {
        $res = DB::table('setting_sys')->where('key', 'is_smoke_alarm')->value('value');
        return $res;
    }

    /*修改默认模板*/
    public function updateExcelPos(){

        $excels = DB::table('a_excel_pos as a')->leftJoin('a_std_tool_rel as b','a.std_tool_rel_id','=','b.id')->where('a.is_default',1)->select('a.id','b.tool_id','b.std_id')->get();
        foreach ($excels as $item){
            DB::table('a_std_tool_item_rel')->where([
                'std_id' => $item->std_id,
                'tool_id' => $item->tool_id,
            ])->update(['excel_pos_id'=>$item->id]);

        }
    }
}
